package encaps.entities;

import encaps.utils.DatabaseUtil;
import encaps.utils.StringUtil;
import java.sql.*;
import java.util.Date;
import java.util.*;
import javax.ejb.*;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class Movie implements EntityBean {

    public static final String TABLE_NAME = "movie";
    public static final String TITLE = "title";
    public static final String PIC = "pic";
    public static final String RUSRELDATE = "russianReleaseDate";
    public static final String WORLDRELDATE = "worldReleaseDate";
    public static final String PRODCOUNTRIES = "producingCountries";
    public static final String STUDIO = "studio";
    public static final String RUSCASH = "russianCash";
    public static final String WORLDCASH = "worldCash";
    public static final String LENGTH = "length";
    public static final String DESCRIPTION = "description";
    public static final String RATING = "rating";
    public static final String NVOTES = "numberVotes";
    private EntityContext context;
    private DataSource dataSource;
    private boolean isEdited;
    private Date russianReleaseDate;
    private Date worldReleaseDate;
    private String producingCountries;
    private String studio;
    private Integer budget;
    private Integer worldCash;
    private Integer length;
    private Long id;
    private String name;
    private String picture;
    private String descript;
    private Double rating;
    private Integer nvotes;
    private Set genres;
    private LinkedList<Comment> comments;
    private HashSet<MoviePersonInfo> persons;

    public void setEntityContext(EntityContext aContext) {
        context = aContext;
        try {
            dataSource = DatabaseUtil.getDataSource();
            isEdited = false;
        } catch (NamingException e) {
            throw new EJBException("DataSource lookup error", e);
        }

    }

    /**
     * @see javax.ejb.EntityBean#ejbActivate()
     */
    public void ejbActivate() {
    }

    /**
     * @see javax.ejb.EntityBean#ejbPassivate()
     */
    public void ejbPassivate() {
    }

    /**
     * @see javax.ejb.EntityBean#ejbRemove()
     */
    public void ejbRemove() throws RemoveException {
        PreparedStatement ps = null;
        Connection conn = null;
        try {
            conn = dataSource.getConnection();
            ps = conn.prepareStatement("DELETE FROM movie_person WHERE movie_id=?");
            ps.setLong(1, id);
            ps.executeUpdate();
            /*
             * if(ps.executeUpdate() < 1) { // throw new
             * RemoveException("Deletion error. Id="+id);
            }
             */
            ps = conn.prepareStatement("DELETE FROM movie WHERE id=?");
            ps.setLong(1, id);
            if (ps.executeUpdate() < 1) {
                throw new RemoveException("Movie delete error. Id=" + id);
            }
            isEdited = false;
        } catch (SQLException ex) {
            throw new EJBException("Error in Movie.ejbRemove method", ex);
        } finally {
            DatabaseUtil.closeConnection(conn, ps);
        }

    }

    public Long ejbCreate(String name, String picture, String descript, HashSet genres, HashSet persons, Date russianReleaseDate,
            Date worldReleaseDate, String producingCountries, String studio, Integer budget, Integer worldCash,
            Integer length) throws CreateException {

        PreparedStatement ps = null;
        PreparedStatement getPersonName = null;
        Connection conn = null;
        try {
            this.picture = picture;
            this.name = name;
            this.descript = descript;
            this.genres = genres;
            this.russianReleaseDate = russianReleaseDate;
            this.worldReleaseDate = worldReleaseDate;
            this.producingCountries = producingCountries;
            this.studio = studio;
            this.budget = budget;
            this.worldCash = worldCash;
            this.length = length;
            this.persons = persons;
            conn = dataSource.getConnection();
            ps = conn.prepareStatement("INSERT INTO movie(title, pic, russianReleaseDate"
                    + ", worldReleaseDate, producingCountries, studio, russianCash, worldCash, length, description) "
                    + "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            ps.setString(1, name);
            ps.setString(2, picture);
            ps.setDate(3, new java.sql.Date(russianReleaseDate.getTime()));
            ps.setDate(4, new java.sql.Date(worldReleaseDate.getTime()));
            ps.setString(5, producingCountries);
            ps.setString(6, studio);
            ps.setInt(7, budget);
            ps.setInt(8, worldCash);
            ps.setInt(9, length);
            ps.setString(10, descript);
            if (ps.executeUpdate() != 1) {
                throw new CreateException("Insert error");
            }
            ps = conn.prepareStatement("SELECT LAST_INSERT_ID()");
            ResultSet rs = ps.executeQuery();
            if (!rs.next()) {
                throw new CreateException("Insert error");
            }
            id = rs.getLong(1);
            if (genres != null && !genres.isEmpty()) {
                Iterator genr = genres.iterator();
                ps = conn.prepareStatement("INSERT INTO movie_genre(movie_id, genre) VALUES(?, ?)");
                while (genr.hasNext()) {
                    ps.setLong(1, id);
                    ps.setString(2, (String) genr.next());
                    if (ps.executeUpdate() != 1) {
                        throw new CreateException("Insert genres error");
                    }
                }
            }
            if (persons != null && !persons.isEmpty()) {
                ps = conn.prepareStatement("INSERT INTO movie_person(movie_id, person_id, type) VALUES(?, ?, ?)");
                getPersonName = conn.prepareStatement("SELECT name FROM person WHERE id=?");
                Iterator pers = persons.iterator();
                MoviePersonInfo person;
                while (pers.hasNext()) {
                    person = (MoviePersonInfo) pers.next();
                    ps.setLong(1, id);
                    ps.setLong(2, person.id);
                    ps.setString(3, person.type);
                    if (ps.executeUpdate() != 1) {
                        throw new CreateException("Insert persons error");
                    }
                    getPersonName.setLong(1, person.id);
                    ResultSet rr = getPersonName.executeQuery();
                    if (rr.next()) {
                        person.name = rr.getString(1);
                    }
                }
            }
            isEdited = false;
            return id;
        } catch (Exception ex) {
            throw new EJBException("Error in Movie.ejbCreate method", ex);
        } finally {
            DatabaseUtil.closeConnection(null, getPersonName);
            DatabaseUtil.closeConnection(conn, ps);
        }

    }

    public void ejbPostCreate(String name, String picture, String descript, HashSet genres, HashSet persons, Date russianReleaseDate,
            Date worldReleaseDate, String producingCountries, String studio, Integer budget, Integer worldCash,
            Integer length) throws CreateException {
    }

    /**
     * @see javax.ejb.EntityBean#unsetEntityContext()
     */
    public void unsetEntityContext() {
        context = null;
    }

    /**
     * @see javax.ejb.EntityBean#ejbLoad()
     */
    public void ejbLoad() {
        id = (Long) context.getPrimaryKey();
        PreparedStatement ps = null;
        Connection conn = null;
        try {
            conn = dataSource.getConnection();
            ps = conn.prepareStatement("SELECT title, description, pic, rating, russianReleaseDate"
                    + ", worldReleaseDate, producingCountries, studio, russianCash, worldCash, length, numberVotes FROM movie WHERE id=?");
            ps.setLong(1, id);
            ResultSet rs = ps.executeQuery();
            if (!rs.next()) {
                throw new NoSuchEntityException("No movie found by id = " + id);
            }
            picture = rs.getString(PIC);
            name = rs.getString(TITLE);
            descript = rs.getString(DESCRIPTION);
            rating = rs.getDouble(RATING);
            russianReleaseDate = rs.getDate(RUSRELDATE);
            worldReleaseDate = rs.getDate(WORLDRELDATE);
            producingCountries = rs.getString(PRODCOUNTRIES);
            studio = rs.getString(STUDIO);
            budget = rs.getInt(RUSCASH);
            worldCash = rs.getInt(WORLDCASH);
            length = rs.getInt(LENGTH);
            nvotes = rs.getInt(NVOTES);
// RETRIEVE GENRES
            ps = conn.prepareStatement("SELECT genre FROM movie_genre WHERE movie_id=?");
            ps.setLong(1, id);
            rs = ps.executeQuery();
            genres = new HashSet();
            while (rs.next()) {
                genres.add(rs.getString("genre"));
            }
// RETRIEVE PERSONS
            ps = conn.prepareStatement("SELECT person_id, type, name FROM movie_person LEFT JOIN person ON movie_person.person_id=person.id WHERE movie_id=? ");
            ps.setLong(1, id);
            rs = ps.executeQuery();
            persons = new HashSet();
            MoviePersonInfo mpi;
            while (rs.next()) {
                mpi = new MoviePersonInfo();
                mpi.id = rs.getLong("person_id");
                mpi.type = rs.getString("type");
                mpi.name = rs.getString("name");
                persons.add(mpi);
            }
// RETRIEVE COMMENTS
            ps = conn.prepareStatement("SELECT comment.id, user_id, content, date, editDate, login FROM comment left join user on comment.user_id=user.id WHERE movie_id=? ORDER BY date DESC");
            ps.setLong(1, id);
            rs = ps.executeQuery();
            comments = new LinkedList();
            Comment c;
            while (rs.next()) {
                Long key = rs.getLong("id");
                Date date = rs.getTimestamp("date");
                Date editDate = rs.getTimestamp("editDate");
                c = new Comment(key, rs.getLong("user_id"), rs.getString("content"), date, rs.getString("login"));
                c.setEditDate(editDate);
                comments.addLast(c);
            }

            isEdited = false;
        } catch (SQLException ex) {
            throw new EJBException("Error in Movie.ejbLoad method", ex);
//        } catch(ParseException ex) {
            //          throw new EJBException("Error in Movie.ejbLoad in getDateOfComment", ex);
        } finally {
            DatabaseUtil.closeConnection(conn, ps);
        }
    }

    /**
     * @see javax.ejb.EntityBean#ejbStore()
     */
    public void ejbStore() {
        if (!isEdited) {
            return;
        }
        PreparedStatement ps = null;
        Connection conn = null;
        try {
            conn = dataSource.getConnection();
            ps = conn.prepareStatement("UPDATE movie SET title=?, pic=?, russianReleaseDate=?"
                    + ", worldReleaseDate=?, producingCountries=?, studio=?, russianCash=?, worldCash=?, length=?, description=? "
                    + " WHERE id=?");
            ps.setString(1, name);
            ps.setString(2, picture);
            ps.setDate(3, (java.sql.Date) russianReleaseDate);
            ps.setDate(4, (java.sql.Date) worldReleaseDate);
            ps.setString(5, producingCountries);
            ps.setString(6, studio);

            ps.setObject(7, budget);
            ps.setObject(8, worldCash);
            ps.setObject(9, length);
            //ps.setInt(7, budget);
            //ps.setInt(8, worldCash);
            //ps.setLong(9, length);
            ps.setString(10, descript);
            ps.setLong(11, id);
            if (ps.executeUpdate() < 1) {
                throw new NoSuchEntityException("No movie found by id = " + id);
            }

// UPDATE MOVIE_GENRE            
            ps = conn.prepareStatement("DELETE FROM movie_genre WHERE movie_id=?");
            ps.setLong(1, id);
            if (ps.executeUpdate() < 1) {
                //throw new NoSuchEntityException("Error On ejbStore genre_remove by movie_id = " + id);
            }
            if (genres != null && !genres.isEmpty()) {
                ps = conn.prepareStatement("INSERT INTO movie_genre(movie_id, genre) VALUES(?, ?)");
                ps.setLong(1, id);
                Iterator gens = genres.iterator();
                while (gens.hasNext()) {
                    ps.setString(2, (String) gens.next());
                    if (ps.executeUpdate() != 1) {
                        throw new NoSuchEntityException("No movie_genre found by id = " + id);
                    }
                }
            }

// UPDATE MOVIE_PERSON            
            ps = conn.prepareStatement("DELETE FROM movie_person WHERE movie_id=?");
            ps.setLong(1, id);
            if (ps.executeUpdate() < 1) {
//                 throw new NoSuchEntityException("Error On ejbStore person_remove by movie_id = " + id);
            }
            if (persons != null && !persons.isEmpty()) {
                ps = conn.prepareStatement("INSERT INTO movie_person(movie_id, person_id, type) VALUES(?, ?, ?)");
                ps.setLong(1, id);
                Iterator pers = persons.iterator();
                MoviePersonInfo mpi;
                while (pers.hasNext()) {
                    mpi = (MoviePersonInfo) pers.next();
                    ps.setLong(2, mpi.id);
                    ps.setString(3, mpi.type);
                    if (ps.executeUpdate() != 1) {
                        throw new NoSuchEntityException("No movie_person found by id = " + id);
                    }
                }
            }

            isEdited = false;

        } catch (SQLException ex) {
            throw new EJBException("Error in Movie.ejbStore method", ex);
        } finally {
            DatabaseUtil.closeConnection(conn, ps);
        }
    }

    public Collection ejbFindAll() {
        PreparedStatement ps = null;
        Connection conn = null;
        try {
            conn = dataSource.getConnection();
            ps = conn.prepareStatement("SELECT id FROM Movie");
            Collection keys = new LinkedList();
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                keys.add(rs.getLong(1));
            }
            return keys;
        } catch (SQLException ex) {
            throw new EJBException("Error in Movie.ejbFindAll method", ex);
        } finally {
            DatabaseUtil.closeConnection(conn, ps);
        }
    }

// HARDCORE ^_^    
    public Collection ejbFindPaged(String title, String sortColumn,
            OrderType orderType, Integer from, Integer count) {
        PreparedStatement ps = null;
        Connection conn = null;
        try {
            conn = dataSource.getConnection();
            String queryPattern = "SELECT id FROM Movie WHERE title LIKE ? %s LIMIT ?, ?";
            String orderClause;
            if (!StringUtil.isEmpty(sortColumn)) {
                StringBuilder sb = new StringBuilder();
                sb.append("ORDER BY ");
                sb.append(sortColumn);
                if (orderType.toString() != null) {
                    sb.append(" ");
                    sb.append(orderType.toString());
                }
                sb.append(" ");
                orderClause = sb.toString();
            } else {
                orderClause = "";
            }
            String queryString = String.format(queryPattern, orderClause);


            ps = conn.prepareStatement(queryString);
            String titleLike;
            titleLike = StringUtil.getLikePattern(title);
            ps.setString(1, titleLike);
            ps.setInt(2, from);
            ps.setInt(3, count);
            Collection keys = new LinkedList();
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                keys.add(rs.getLong(1));
            }
            return keys;
        } catch (SQLException ex) {
            throw new EJBException("Error in Movie.ejbFindAllPaged method", ex);
        } finally {
            DatabaseUtil.closeConnection(conn, ps);
        }
    }

    public Collection ejbFindByParametersPaged(String title, String producingCountries,
            String genre, String personName, String studio, Double ratingMin,
            Double ratingMax, String description, Integer budgetMin, Integer budgetMax,
            Integer worldCashMin, Integer worldCashMax, String orderColumn,
            OrderType orderType, int from, int count) throws FinderException {

        PreparedStatement ps = null;
        Connection conn = null;
        try {
            conn = dataSource.getConnection();
            String queryString = StringUtil.constructMovieSearchQuery(
                    "DISTINCT movie.id", title, producingCountries,
                    genre, personName, studio, ratingMin, ratingMax, description,
                    budgetMin, budgetMax, worldCashMin, worldCashMax,
                    orderColumn, orderType, from, count);
            ps = conn.prepareStatement(queryString);
            Collection keys = new LinkedList();
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                keys.add(rs.getLong(1));
            }
            return keys;
        } catch (SQLException ex) {
            throw new EJBException("Error in Movie.ejbFindAllPaged method", ex);
        } finally {
            DatabaseUtil.closeConnection(conn, ps);
        }
    }

    public Integer ejbHomeGetMoviesCount(String title, String producingCountries,
            String genre, String personName, String studio, Double ratingMin,
            Double ratingMax, String description, Integer budgetMin, Integer budgetMax,
            Integer worldCashMin, Integer worldCashMax) throws FinderException {
        PreparedStatement ps = null;
        Connection conn = null;
        try {
            conn = dataSource.getConnection();
            String queryString = StringUtil.constructMovieSearchQuery(
                    "count(DISTINCT movie.id)", title, producingCountries,
                    genre, personName, studio, ratingMin, ratingMax, description,
                    budgetMin, budgetMax, worldCashMin, worldCashMax, null, null, null, null);
            ps = conn.prepareStatement(queryString);
            ResultSet rs = ps.executeQuery();
            rs.first();
            return rs.getInt(1);
        } catch (SQLException ex) {
            throw new EJBException("Error in Movie.getMoviesCount method", ex);
        } finally {
            DatabaseUtil.closeConnection(conn, ps);
        }
    }

    // </editor-fold>
    /**
     * See EJB 2.0 and EJB 2.1 section 12.2.5
     */
    public java.lang.Long ejbFindByPrimaryKey(java.lang.Long key) throws FinderException {
        PreparedStatement ps = null;
        Connection conn = null;
        try {
            conn = dataSource.getConnection();
            ps = conn.prepareStatement("SELECT id FROM movie WHERE id=?;");
            ps.setLong(1, key);
            ResultSet rs = ps.executeQuery();
            if (!rs.next()) {
                throw new ObjectNotFoundException("No movie found by primary key = " + key);
            }
            return key;
        } catch (SQLException ex) {
            throw new EJBException("Error in Movie.ejbFindByPrimaryKey method", ex);
        } finally {
            DatabaseUtil.closeConnection(conn, ps);
        }
    }

    public HashSet<MoviePersonInfo> getPersons() {
        return persons;
    }

    public void setPersons(HashSet<MoviePersonInfo> persons) {
        this.persons = persons;
        isEdited = true;
    }

    public Long getId() {
        return id;
    }

    public String getTitle() {
        return name;
    }

    public void setTitle(String title) {
        this.name = title;
        isEdited = true;
    }

    public String getPicture() {
        return picture;
    }

    public void setPicture(String picture) {
        this.picture = picture;
        isEdited = true;
    }

    public String getDescription() {
        return descript;
    }

    public void setDescription(String descript) {
        this.descript = descript;
        isEdited = true;
    }

    public Date getRussianReleaseDate() {
        return russianReleaseDate;
    }

    public void setRussianReleaseDate(Date russianReleaseDate) {
        if (russianReleaseDate == null) {
            this.russianReleaseDate = null;
        } else {
            this.russianReleaseDate = new java.sql.Date(russianReleaseDate.getTime());
        }
        isEdited = true;
    }

    public Date getWorldReleaseDate() {
        return worldReleaseDate;
    }

    public void setWorldReleaseDate(Date worldReleaseDate) {
        if (worldReleaseDate == null) {
            this.worldReleaseDate = null;
        } else {
            this.worldReleaseDate = new java.sql.Date(worldReleaseDate.getTime());
        }
        isEdited = true;
    }

    public String getCountries() {
        return producingCountries;
    }

    public void setCountries(String producingCountries) {
        this.producingCountries = producingCountries;
        isEdited = true;
    }

    public String getStudio() {
        return studio;
    }

    public void setStudio(String studio) {
        this.studio = studio;
        isEdited = true;
    }

    public Integer getBudget() {
        return budget;
    }

    public void setBudget(Integer budget) {
        this.budget = budget;
        isEdited = true;
    }

    public Integer getWorldCash() {
        return worldCash;
    }

    public void setWorldCash(Integer worldCash) {
        this.worldCash = worldCash;
        isEdited = true;
    }

    public Integer getLength() {
        return length;
    }

    public void setLength(Integer length) {
        this.length = length;
        isEdited = true;
    }

    public void setGenres(HashSet genres) {
        this.genres = genres;
        isEdited = true;
    }

    public String getGenres() {
        String g = genres.toString();
        return g.substring(1, g.length() - 1);
    }

    public Integer getNvotes() {
        return nvotes;
    }

    public String stringRepresentation() {
        StringBuilder sb = new StringBuilder();
        sb.append(getClass().getName());
        sb.append(": [");
        sb.append("id=");
        sb.append(id);
        sb.append(", name=");
        sb.append(name);
        sb.append(", descript=");
        sb.append(descript);
        sb.append(", picture=");
        sb.append(picture);
        sb.append(", genres=");
        sb.append(getGenres());
        sb.append(", rating=");
        sb.append(rating);
        sb.append(", relDate=");
        sb.append(russianReleaseDate);
        sb.append("]");
        return sb.toString();
    }

    public Long addComment(Long user_id, String content, Date date) throws CreateException {
        PreparedStatement ps = null;
        Connection conn = null;
        try {
            conn = dataSource.getConnection();
            Timestamp dateTime = new Timestamp(date.getTime());
            ps = conn.prepareStatement("INSERT INTO comment(user_id, movie_id, content, date, editDate) "
                    + "VALUES(?, ?, ?, ?, ?)");
            ps.setLong(1, user_id);
            ps.setLong(2, id);
            ps.setString(3, content);
            ps.setTimestamp(4, dateTime);
            ps.setTimestamp(5, dateTime);
            if (ps.executeUpdate() != 1) {
                throw new CreateException("Insertion error");
            }
            ps = conn.prepareStatement("SELECT LAST_INSERT_ID()");
            ResultSet rs = ps.executeQuery();
            if (!rs.next()) {
                throw new CreateException("Insertion error 2");
            }
            Long key = rs.getLong(1);
            ps = conn.prepareStatement("SELECT login FROM user WHERE id=?");
            ps.setLong(1, user_id);
            rs = ps.executeQuery();
            rs.next();
            comments.addLast(new Comment(key, user_id, content, date, rs.getString(1)));
            return key;
        } catch (SQLException ex) {
            throw new EJBException("Error in Movie.addComment method", ex);
        } finally {
            DatabaseUtil.closeConnection(conn, ps);
        }
    }

    private Comment commentWalker(Long id) {
        Iterator i = comments.iterator();
        Comment c = null;
        while (i.hasNext()) {
            c = (Comment) i.next();
            if (c.getId().equals(id)) {
                break;
            }
        }
        return c;
    }

    public void removeComment(Long comment_id) throws RemoveException {
        PreparedStatement ps = null;
        Connection conn = null;
        try {
            conn = dataSource.getConnection();
            ps = conn.prepareStatement("DELETE FROM comment WHERE id=?");
            ps.setLong(1, comment_id);
            if (ps.executeUpdate() < 1) {
                throw new NoSuchEntityException("No comment found by id = " + comment_id);
            }
            Comment c = commentWalker(comment_id);
            comments.remove(c);
        } catch (SQLException ex) {
            throw new EJBException("Error in Movie.removeComment method", ex);
        } finally {
            DatabaseUtil.closeConnection(conn, ps);
        }
    }

    public void updateComment(Long comment_id, String content, Date date) {
        PreparedStatement ps = null;
        Connection conn = null;
        try {
            conn = dataSource.getConnection();
            ps = conn.prepareStatement("UPDATE comment SET content=?, editDate=? WHERE id=?");
            ps.setString(1, content);
            ps.setTimestamp(2, new Timestamp(date.getTime()));
            ps.setLong(3, comment_id);
            if (ps.executeUpdate() < 1) {
                throw new NoSuchEntityException("No comment found by id = " + comment_id);
            }
            Comment editedComment = commentWalker(comment_id);
            editedComment.setContent(content);
            editedComment.setEditDate(date);
        } catch (SQLException ex) {
            throw new EJBException("Error in Movie.updateComment method", ex);
        } finally {
            DatabaseUtil.closeConnection(conn, ps);
        }
    }

    public LinkedList<Comment> getComments() {
        return comments;
    }

    public Double getRating() {
        return rating;
    }

    public Integer ejbHomeGetMoviesCount(String title) throws FinderException {
        PreparedStatement ps = null;
        Connection conn = null;
        try {
            conn = dataSource.getConnection();
            ps = conn.prepareStatement("SELECT Count(id) FROM Movie WHERE title LIKE ?");
            String titleLike = StringUtil.getLikePattern(title);
            ps.setString(1, titleLike);
            ResultSet rs = ps.executeQuery();
            rs.first();
            return rs.getInt(1);
        } catch (SQLException ex) {
            throw new EJBException("Error in Movie.getMoviesCount method", ex);
        } finally {
            DatabaseUtil.closeConnection(conn, ps);
        }
    }

    public void addRating(Double rating, Long user_id, Date date) throws CreateException {
        PreparedStatement ps = null;
        Connection conn = null;
        try {
            conn = dataSource.getConnection();
            Timestamp dateTime = new Timestamp(date.getTime());
// INSERT RATING            
            ps = conn.prepareStatement("INSERT INTO USER_RATING(user_id, movie_id, rating, date) "
                    + "VALUES(?, ?, ?, ?)");
            ps.setLong(1, user_id);
            ps.setLong(2, id);
            ps.setDouble(3, rating);
            ps.setTimestamp(4, dateTime);
            if (ps.executeUpdate() != 1) {
                throw new CreateException("Insertion error");
            }
// READ RATING            
            ps = conn.prepareStatement("SELECT rating FROM movie WHERE id=?");
            ps.setLong(1, id);
            ResultSet rs = ps.executeQuery();
            if (!rs.next()) {
                throw new CreateException("Select rating error");
            }
            this.rating = rs.getDouble(1);
        } catch (SQLException ex) {
            throw new EJBException("Error in Movie.addRating method", ex);
        } finally {
            DatabaseUtil.closeConnection(conn, ps);
        }
    }
}